// Global library object. This must be valid for libraries to work!
var lib;

/** The current theme of the widget */
var theme;

/** The main form of the widget */
var frmMain;

var categoryButtons;

var newsLabels;

var searchButton;
var searchField;

var app;

/** Startup code for the widget.
 * Checks to see if the Yahoo Widget Library is properly installed in the system.
 */
function widget_onLoad() {
	var libraryPath;
	var libraryFile;

	// Verify that the library is where we expect it to be.
	libraryPath = system.userWidgetsFolder + "/Library";
	libraryFile = libraryPath + "/LibraryShared.js";
	if(filesystem.itemExists(libraryFile) == true) {
		//load the library 
		include(libraryFile);
		lib = new Yahoo.Utility.Library(libraryPath);
		//call the main routine
		app = new Application(15);
		app.main();
	}
	else {
		alert("This widget requires components from the Widget Class Library.\n\nPlease verify that the required files been successfully installed in the My Widgets folder.");
	}
}

function Application(rssCacheSize) {
	//create a new RSSCache object
	this.rssCache = new RSSCache(rssCacheSize);
	
	//create a new DatabaseAccess object
	this.databaseHandler = new DatabaseAccess();
	
	//create the LearningComponent object
	this.learner = new SOM(this.categoryNumber, this.databaseHandler);
	
	//create the database if not available
	this.databaseHandler.createDatabase();
	
	//open the database
	this.databaseHandler.openDatabase();
	
	//get the preffered categories
	var result = this.databaseHandler.getPrefferedCategories(this.categoryNumber);
	
	//get the news for the first category
	this.selectedKey = 0;
	this.searchedAddress = null;
	
	//create the structures for preffered category
	this.categoryIds = new Array(this.categoryNumber);
	this.categoryRss = new Array(this.categoryNumber);
	this.categoryName = new Array(this.categoryNumber);
	
	for(i = 0;i < this.categoryNumber;i++) {	
		this.categoryIds[i] = result[i][0];
		this.categoryRss[i] = result[i][1];
		this.categoryName[i] = result[i][2];
		this.learner.addNode(new SOMNode(result[i][0], result[i][3], result[i][4], result[i][5]));
	}
}

Application.prototype.main = application_main;
Application.prototype.reloadNews = application_reloadNews;
Application.prototype.exit = application_exit;
Application.prototype.getBestNews = application_getBestNews;
Application.prototype.getSearchedNews = application_getSearchedNews;
Application.prototype.categoryNumber = 8;
Application.prototype.topPadding = 25;
Application.prototype.labelHeight = 25;
Application.prototype.buttonHeight = 25;
Application.prototype.buttonWidth = 120;
Application.prototype.leftPadding = 15;
Application.prototype.newsNumber = 10;
Application.prototype.newsTitleLength = 60;

function application_exit() {
	this.databaseHandler.closeDatabase();
}

function application_main() {

	/** Includes from the library */
	lib.include("Yahoo.Resources.ResourceManager");
	lib.include("Yahoo.Drawing.ContentAlignment");
	lib.include("Yahoo.Drawing.Common");
	lib.include("Yahoo.EventArgs");
	lib.include("Yahoo.Controls.Theme");
	lib.include("Yahoo.Controls.Control");
	lib.include("Yahoo.Controls.SizableControlBase");
	lib.include("Yahoo.Controls.Sizable3PartControlBase");
	//lib.include("Yahoo.Controls.CheckBoxBase");
	//lib.include("Yahoo.Controls.CheckBox");
	lib.include("Yahoo.Controls.Label");
	lib.include("Yahoo.Controls.Button");
	//lib.include("Yahoo.Controls.ComboBox");
	//lib.include("Yahoo.Controls.ImageComboBox");
	//lib.include("Yahoo.Controls.CheckedListBox");
	//lib.include("Yahoo.Controls.ProgressBar");
	lib.include("Yahoo.Controls.TextBox");
	lib.include("Yahoo.Controls.Form");
	
	//create the Theme
	theme = new Yahoo.Controls.Theme(lib.getClassResourcePath("Yahoo.Controls") + "/Themes");
    theme.loadTheme("Black Glass");
	
	// Listen to theme changed events
	theme.addEventHandler(theme_onThemeChanged, "ThemeChanged");
	
	initMainForm();
}

function initMainForm() {
	frmMain = new Yahoo.Controls.Form(theme);
	frmMain.text = "Adaptive Newsletter";
	frmMain.width = 550;
	frmMain.height = 350;
	frmMain.left = (screen.availWidth / 2) - (frmMain.width / 2);
	frmMain.top = (screen.availHeight / 2) - (frmMain.height / 2);
	frmMain.formBorderStyle = Yahoo.Controls.FormBorderStyle.Sizable;
	frmMain.minimumSize = new Yahoo.Drawing.Size(550,350);
	frmMain.maximumSize = new Yahoo.Drawing.Size(550,600);
	frmMain.addEventHandler(frmMain_onClosed, "Closed");
	frmMain.addEventHandler(frmMain_onResize, "Resize");
	frmMain.window.level = "topmost";
	
	createCategoryButtons();
	createLowerPannel();
	createNewsLabels();
	frmMain.show();
}

function createCategoryButtons() {
	categoryButtons = new Array(app.categoryNumber);
	
	for(i = 0;i < app.categoryNumber;i++) {
		categoryButtons[i] = new Yahoo.Controls.Button(frmMain.theme);
		categoryButtons[i].left = app.leftPadding;
		categoryButtons[i].top = i * 30 + app.topPadding;
		categoryButtons[i].width = app.buttonWidth;
		categoryButtons[i].height = app.buttonHeight;
		categoryButtons[i].text = app.categoryName[i];
		categoryButtons[i].textAlign = Yahoo.Drawing.ContentAlignment.MiddleCenter;
		categoryButtons[i].addEventHandler(categorybButton_onClick, "Click");
		categoryButtons[i].key = i;
		frmMain.addControl(categoryButtons[i]);
	}
}

function createLowerPannel() {
	searchButton = new Yahoo.Controls.Button(frmMain.theme);
	searchButton.left = app.leftPadding;
	searchButton.top = app.categoryNumber * 30 + app.topPadding;
	searchButton.text = "Search";
	searchButton.width = app.buttonWidth;
	searchButton.height = app.buttonHeight;
	searchButton.textAlign = Yahoo.Drawing.ContentAlignment.MiddleCenter;
	searchButton.addEventHandler(searchButton_onClick, "Click");
	frmMain.addControl(searchButton);
	
	searchField = new Yahoo.Controls.TextBox(frmMain.theme);
	searchField.left = app.buttonWidth + 25;
	searchField.top = app.categoryNumber * 30 + app.topPadding;
	searchField.width = 150;
	searchField.height = app.buttonHeight;
	searchField.text = "Type here...";
	searchField.addEventHandler(searchField_onEnter, "Enter");
	searchField.addEventHandler(searchField_onKeyDown, "KeyDown");
	frmMain.addControl(searchField);
}

function createNewsLabels() {
	newsLabels = new Array(app.newsNumber);
	
	for(i = 0;i < app.newsNumber;i++) {
		newsLabels[i] = new Yahoo.Controls.Label(frmMain.theme);
		newsLabels[i].autoSize = true;
		newsLabels[i].left = app.leftPadding + app.buttonWidth + app.leftPadding;
		newsLabels[i].top = i * 20 + app.topPadding;
		newsLabels[i].height = app.labelHeight;
		newsLabels[i].text = "miau miau";
		newsLabels[i].addEventHandler(newsLabel_onClick, "Click");
		newsLabels[i].key = i;
		frmMain.addControl(newsLabels[i]);
	}
	app.reloadNews();
}

function application_reloadNews() {
	if(this.selectedKey >= 0) {
		this.currentNewsList = this.rssCache.get(this.categoryRss[this.selectedKey]);
	} else if(this.searchedAddress != null){
		this.getBestNews();
	} else {
		this.currentNewsList = new NewsHeaderList();
		this.currentNewsList.add(new NewsHeader("No results found", null, null, null));
	}
	for(i = 0;i < newsLabels.length;i++) {
		if(i < this.currentNewsList.length()) {
			newsLabels[i].text = processEntityTitle(this.currentNewsList.items[i].title); 
		} else {
			newsLabels[i].text = "";
		}
	}
}

function processEntityTitle(title) {
	var result = replaceHtmlEntites(title);
	if(result.length > app.newsTitleLength) {
		result = result.substr(0, app.newsTitleLength) + "...";
	}
	return result;
}

function application_getSearchedNews(text) {
	var result = this.databaseHandler.getAddressByWord(text);
	if(result == null) {
		result = this.databaseHandler.getAddressByName(text);
	}
	this.selectedKey = -1;
	if(result != null) {
		this.searchedAddress = result;
	} else {
		this.searchedAddress = null;
	}
	this.reloadNews();
}

function application_getBestNews() {
	for(i = 0;i < this.searchedAddress.length;i++) {
		this.currentNewsList = this.rssCache.get(this.searchedAddress[i][1]);
		if(this.currentNewsList.length() > 1) {
			break;
		}
	}
}

/*  original code of Jason Bunting */
/* ------------------------------------------- */
var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ", 
    "amp" : "&", 
    "quot": "\"",
    "lt"  : "<", 
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) { 
      return translate[entity]; 
    }) );
  }
})();
/* ------------------------------------------- */

/** Section Handlers */

/**
 * Handles onClosed event for form.
 */
function frmMain_onClosed(sender, e) {
	app.exit();
	closeWidget();
}

/**
 * Handles theme onThemeChanged event.
 */
function theme_onThemeChanged(sender, e) {
    // Set theme on main form
    frmMain.theme = sender;
}

/**
 * Handles onResize event for form.
 */
function frmMain_onResize(sender, e) {
	//doLayout();
}

function categorybButton_onClick(sender, e) {
	app.selectedKey = sender.key;
	app.reloadNews();
	var categId = app.categoryIds[sender.key];
	var node = app.learner.getNodeById(categId);
	app.learner.updateSOM(node);
	app.learner.updateCategory(categId);
}

function searchButton_onClick(sender, e) {
	app.getSearchedNews(searchField.text);
}

function searchField_onEnter(sender, e) {
	sender.text = "";
}

function searchField_onKeyDown(sender, e) {
	if(e.keyString == "Return") {
		app.getSearchedNews(searchField.text);
	}
}

function newsLabel_onClick(sender, e) {
	if(sender.key < app.currentNewsList.length()) {
		if(app.currentNewsList.items[sender.key].url != null) {
			openURL(app.currentNewsList.items[sender.key].url);
		}
	}
}